﻿using com.ytocargo.Application.BackgroundJobs;
using com.ytocargo.Application.ChartsInPeriods;
using com.ytocargo.Core.SystemSettings;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yto.Common;
using Yto.Common.Dependency;

namespace com.ytocargo.Application.SystemSettings
{
    public class SystemSettingsServices : ISystemSettingsServices, ITransient
    {
        private readonly IBackgroundJobManager _jobManager;

        public SystemSettingsServices(IBackgroundJobManager jobManager)
        {
            _jobManager = jobManager;
        }
        public async Task ReadCsvFile()
        {
            string strFilePath = ConfigurationManager.AppSettings["CsvPathToUpdate"];
            string strFileName = ConfigurationManager.AppSettings["SysSettingFile"];
            string EffectiveDate = ConfigurationManager.AppSettings["EffectiveDate"];

            if(FileHelper.FileExist(strFilePath + strFileName))
            {
                DataTable dt = CsvFileHelper.OpenCsv(strFilePath + strFileName);

                var list = CsvFileHelper.GetList<SystemSetting>(strFilePath + strFileName);

                var item = list.Find(s => s.KEYNAME == EffectiveDate);

                if(item != null)
                {
                    if (DateTime.TryParse(item.KEYVALUE, out DateTime effectiveDateTime))
                    {
                        await _jobManager.EnqueueAsync<InPeriodWorker, InPeriodWorkerArgs>(
                            new InPeriodWorkerArgs(), effectiveDateTime
                            );
                    }
                }
            }
        }
    }
}
